<template>
  <a-select
    :placeholder="selectPlaceholder"
    v-model="selectId"
    allow-clear
    :show-header-on-empty="true"
    @clear="handelClear as any"
    @change="handelChange as any"
    @popup-visible-change="popupVisibleChange"
  >
    <template #header>
      <div class="search-select-container">
        <a-input
          v-autoFocus
          style="border: 0"
          allow-clear
          :placeholder="placeholder"
          v-model="keyword"
          @press-enter="handleSearchSelect"
        />
        <GiSvgIcon name="searchBox-icon" size="24" style="margin-right: 18px; cursor: pointer" @click="handleSearchSelect" />
      </div>
    </template>
    <a-option v-for="optItem in selectList" :value="optItem[config.value]" :key="optItem[config.value]">
      {{ optItem[config.label] }}
    </a-option>
  </a-select>
</template>

<script setup lang="ts">
import { debounce, isEmpty } from "lodash";
const props = defineProps({
  /**
   * 输入框占位
   */
  placeholder: {
    type: String,
    default: "请输入关键词"
  },
  /**
   * 选择框占位
   */
  selectPlaceholder: {
    type: String,
    default: "请输入"
  },
  /**
   * 默认选中值
   */
  defaultSelectId: {
    type: String
  },
  /**
   * 默认选中列表
   */
  defaultSelectList: {
    type: Array
  },
  /**
   * 请求接口
   */
  requestApi: {
    type: Function,
    required: true
  },
  /**
   * 请求参数
   */
  params: {
    type: Object,
    default: () => ({})
  },
  /**
   * 配置项
   */
  config: {
    type: Object,
    default: () => ({})
  },
  /**
   * 循环索引
   */
  index: {
    type: Number,
    default: -1
  },
  /**
   * 是否首次加载
   */
  isFirstLoad: Boolean
});
const emit = defineEmits(["changeSelect", "clearSelected"]);

const config = ref({
  label: "label",
  value: "value",
  keyword: "keyword",
  debounceTime: 500,
  ...props.config
});
const keyword = ref("");
const selectId = ref(props.defaultSelectId);
const selectList = ref(props.defaultSelectList) as any;

const popupVisibleChange = (visible: boolean) => {
  if (visible && props.isFirstLoad) {
    getSelectList();
  }
};

/**
 * 搜索
 */
const getSelectList = async () => {
  const { data } = await props.requestApi({
    [config.value.keyword]: keyword.value,
    ...props.params
  });
  const list = Array.isArray(data) ? data : [];
  const selectItemIndex = list.findIndex(item => item[config.value.value] === selectId.value);
  if (selectItemIndex === -1) {
    list.unshift({ ...(props.defaultSelectList?.length ? (props.defaultSelectList[0] as object) : {}) });
  }
  selectList.value = list;
};
const handleSearchSelect = debounce(getSelectList, config.value.debounceTime);
/**
 * 选择
 */
const handelChange = (e: any) => {
  const selectObj = selectList.value.find((item: any) => item[props.config.value] === e);
  if (!isEmpty(selectObj)) {
    emit("changeSelect", { selectObj, index: props.index });
  }
};

/**
 * 清空选择
 */
const handelClear = () => {
  emit("clearSelected");
};
</script>

<style scoped lang="scss">
@import "selectSearch";
</style>
